<template>
  <div class="study-page">
    <div class="container">
      <!-- 顶部导航栏 -->
      <div class="header">
        <button class="btn btn-secondary" @click="goBack">← 返回单词书</button>
        <div class="progress-info">
          <span>进度: {{ currentIndex + 1 }} / {{ totalWords }}</span>
          <span>当前页: {{ currentPage }}</span>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading">
        <div class="loading-spinner"></div>
        <p>正在加载单词...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-message card">
        <h3>⚠️ 加载失败</h3>
        <p>{{ error }}</p>
        <button class="btn btn-primary" @click="loadWords">重试</button>
      </div>

      <!-- 学习完成 -->
      <div v-else-if="isCompleted" class="completed-state card">
        <div class="completed-icon">🎉</div>
        <h3>恭喜！本轮学习完成</h3>
        <p>已学习 {{ learnedWordIds.length }} 个单词</p>
        <div class="completed-actions">
          <button class="btn btn-primary" @click="loadNextBatch">继续下一轮</button>
          <button class="btn btn-secondary" @click="goBack">返回单词书</button>
        </div>
      </div>

      <!-- 单词卡片 -->
      <div v-else-if="currentWord" class="word-card-container">
        <div class="word-card card">
          <!-- 单词显示 -->
          <div class="word-display">
            <button
              v-if="wordHistory.length > 0"
              class="btn-undo"
              @click="undoLastWord"
              title="撤回上一个单词 (Q)"
            >
              ↶
            </button>
            <h1 class="word-text">{{ currentWord.word }}</h1>
          </div>

          <!-- 释义显示（初始隐藏） -->
          <div v-if="showMeaning" class="word-meaning">
            <div class="meaning-content">
              <div v-for="(sense, index) in currentWord.senses" :key="index" class="sense-item">
                <div class="sense-header">
                  <span class="part-of-speech">{{ sense.pos }}</span>
                </div>
                <p class="definition-cn">{{ sense.definition_cn }}</p>
                <p v-if="sense.definition_en" class="definition-en">{{ sense.definition_en }}</p>
              </div>
            </div>
          </div>

          <!-- 控制按钮 -->
          <div class="word-controls">
            <div v-if="!showMeaning" class="reveal-section">
              <button class="btn btn-primary btn-large" @click="revealMeaning" ref="revealButton">
                查看单词意思 (➡)
              </button>
            </div>

            <div v-else class="action-section">
              <div class="action-buttons">
                <button class="btn btn-danger btn-large" @click="markUnknown" ref="unknownButton">
                  记错了 (⬅)
                </button>
                <button class="btn btn-success btn-large" @click="markKnown" ref="knownButton">
                  认识 (➡)
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 快捷键提示 -->
        <div class="shortcuts-hint">
          <p>快捷键: ⬅ 不认识 | ➡ {{ showMeaning ? '认识' : '查看意思' }} | ⬆ 撤回</p>
        </div>
      </div>

      <!-- 单词记录部分 -->
      <div class="word-records-section">
        <div class="records-header">
          <h3>学习记录</h3>
          <div class="records-stats">
            <span class="stat-item">总计: {{ recordStats.total }}</span>
            <span class="stat-item known">已掌握: {{ recordStats.known }}</span>
            <span class="stat-item unknown">不认识: {{ recordStats.unknown }}</span>
          </div>
          <div class="records-actions">
            <button class="btn btn-secondary btn-small" @click="showRecords = !showRecords">
              {{ showRecords ? '隐藏记录' : '显示记录' }}
            </button>
            <button
              v-if="wordRecords.length > 0"
              class="btn btn-danger btn-small"
              @click="clearAllRecords"
            >
              清空记录
            </button>
          </div>
        </div>

        <div v-if="showRecords" class="records-table-container">
          <div v-if="wordRecords.length === 0" class="empty-records">
            <p>暂无学习记录</p>
          </div>
          <div v-else class="records-table-wrapper">
            <table class="records-table">
              <thead>
                <tr>
                  <th>单词ID</th>
                  <th>单词</th>
                  <th>翻译</th>
                  <th>学习状态</th>
                  <th>学习时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="record in wordRecords" :key="record.id" class="record-row">
                  <td class="word-id">{{ record.id }}</td>
                  <td class="word-name">{{ record.word }}</td>
                  <td class="word-translation">{{ record.translation }}</td>
                  <td class="word-status">
                    <span class="status-badge" :class="record.status">
                      {{
                        record.status === 'known'
                          ? '已掌握'
                          : record.status === 'unknown'
                            ? '不认识'
                            : '未学习'
                      }}
                    </span>
                  </td>
                  <td class="learn-time">{{ formatTime(record.timestamp) }}</td>
                  <td class="actions"></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  getUnlearnedWords,
  markWordsAsEasy,
  type UnlearnedWordsResponse,
  type WordDetail,
} from '@/api/scallop'
import Cookies from 'js-cookie'

// 单词学习记录类型
interface WordRecord {
  id: string
  word: string
  translation: string
  status: 'unknown' | 'known' | 'unlearned'
  timestamp: number
}

const route = useRoute()
const router = useRouter()

// 响应式数据
const words = ref<WordDetail[]>([])
const currentIndex = ref(0)
const currentPage = ref(1)
const totalWords = ref(0)
const loading = ref(false)
const error = ref('')
const showMeaning = ref(false)
const learnedWordIds = ref<string[]>([])
const pendingSubmitIds = ref<{ word: WordDetail; status: 'known' | 'unknown' }[]>([]) // 待提交的单词记录
const isCompleted = ref(false)
const wordHistory = ref<number[]>([]) // 记录单词访问历史
const wordRecords = ref<WordRecord[]>([]) // 单词记录列表
const showRecords = ref(true) // 是否显示记录表格

// 获取书本ID
const bookId = route.params.bookId as string

// 计算属性
const currentWord = ref<WordDetail | null>(null)

// LocalStorage 键名
const STORAGE_KEY = `word_records_${bookId}`

// 计算各状态的单词数量
const recordStats = computed(() => {
  const stats = {
    total: wordRecords.value.length,
    known: 0,
    unknown: 0,
    unlearned: 0,
  }

  wordRecords.value.forEach((record) => {
    stats[record.status]++
  })

  return stats
})

// 键盘事件处理
const handleKeypress = (event: KeyboardEvent) => {
  // 防止在输入框中触发
  if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
    return
  }
  switch (event.key.toLowerCase()) {
    case 'arrowright':
      event.preventDefault()
      if (!showMeaning.value) {
        revealMeaning()
      } else {
        markKnown()
      }
      break
    case 'arrowleft':
      event.preventDefault()
      if (showMeaning.value) {
        markUnknown()
      }
      break
    case 'arrowup':
      event.preventDefault()
      if (wordHistory.value.length > 0) {
        undoLastWord()
      }
      break
  }
}

onMounted(() => {
  // 检查是否有 token
  const token = Cookies.get('auth_token')
  if (!token) {
    router.push('/')
    return
  }

  // 验证bookId
  if (!bookId) {
    error.value = '无效的单词书ID'
    return
  }

  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeypress)

  // 加载本地记录
  loadWordRecords()

  // 加载单词
  loadWords()
})

onUnmounted(() => {
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeypress)
})

// 加载单词数据
const loadWords = async () => {
  loading.value = true
  error.value = ''

  try {
    const response: UnlearnedWordsResponse = await getUnlearnedWords(bookId, currentPage.value, 20)
    console.log('API Response:', response)

    // 从响应中提取单词数据
    const wordsData = response.objects?.map((item) => item.vocab_with_senses) || []

    // 过滤掉本地学习记录中已存在的单词
    const learnedWordIds = new Set(wordRecords.value.map((record) => record.id))
    const filteredWords = wordsData.filter((word) => !learnedWordIds.has(word.vocabulary_id))

    words.value = filteredWords
    totalWords.value = response.total || 0

    console.log(
      `原始单词数: ${wordsData.length}, 过滤后单词数: ${filteredWords.length}, 已学习单词数: ${learnedWordIds.size}`,
    )

    if (words.value.length === 0) {
      isCompleted.value = true
    } else {
      currentWord.value = words.value[0]
      currentIndex.value = 0
      showMeaning.value = false
    }
  } catch (err: any) {
    console.error('加载单词失败:', err)
    error.value = err.response?.data?.message || '网络请求失败，请检查登录状态'
    // 如果是认证错误，跳转回首页
    if (err.response?.status === 401) {
      Cookies.remove('auth_token')
      router.push('/')
    }
  } finally {
    loading.value = false
  }
}

// 显示单词释义
const revealMeaning = () => {
  showMeaning.value = true
}

// 加载本地单词记录
const loadWordRecords = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      wordRecords.value = JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载本地记录失败:', error)
    wordRecords.value = []
  }
}

// 保存单词记录到本地
const saveWordRecord = (word: WordDetail, status: 'known' | 'unknown') => {
  const translation = word.senses?.map((sense) => sense.definition_cn).join('; ') || ''

  // 查找是否已存在记录
  const existingIndex = wordRecords.value.findIndex((record) => record.id === word.vocabulary_id)

  const newRecord: WordRecord = {
    id: word.vocabulary_id,
    word: word.word,
    translation,
    status,
    timestamp: Date.now(),
  }

  if (existingIndex >= 0) {
    // 更新现有记录
    wordRecords.value[existingIndex] = newRecord
  } else {
    // 添加新记录
    wordRecords.value.unshift(newRecord)
  }

  // 保存到 localStorage
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(wordRecords.value))
  } catch (error) {
    console.error('保存本地记录失败:', error)
  }
}

// 清空所有记录
const clearAllRecords = () => {
  if (confirm('确定要清空所有单词记录吗？此操作不可恢复。')) {
    wordRecords.value = []
    localStorage.removeItem(STORAGE_KEY)
  }
}

// 删除单个记录
const deleteRecord = (recordId: string) => {
  const index = wordRecords.value.findIndex((record) => record.id === recordId)
  if (index >= 0) {
    wordRecords.value.splice(index, 1)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(wordRecords.value))
  }
}

// 标记为不认识
const markUnknown = () => {
  if (currentWord.value) {
    // 暂时保存到待提交列表，不立即保存到本地记录
    pendingSubmitIds.value.push({
      word: currentWord.value,
      status: 'unknown',
    })
  }
  goToNext()
}

// 标记为认识
const markKnown = () => {
  if (currentWord.value) {
    learnedWordIds.value.push(currentWord.value.vocabulary_id)
    // 暂时保存到待提交列表，不立即保存到本地记录
    pendingSubmitIds.value.push({
      word: currentWord.value,
      status: 'known',
    })
  }
  goToNext()
}

// 下一个单词
const goToNext = () => {
  console.log('已标记认识的单词:', learnedWordIds.value)
  // 记录当前单词到历史
  wordHistory.value.push(currentIndex.value)

  if (currentIndex.value < words.value.length - 1) {
    currentIndex.value++
    currentWord.value = words.value[currentIndex.value]
    showMeaning.value = false
  } else {
    // 当前批次完成，检查是否需要加载下一批
    submitLearnedWords()
  }
}

// 撤回上一个单词
const undoLastWord = () => {
  if (wordHistory.value.length > 0) {
    const previousIndex = wordHistory.value.pop()!
    const previousWord = words.value[previousIndex]

    if (previousWord) {
      // 如果上一个单词在已学习列表中，则移除
      if (learnedWordIds.value.includes(previousWord.vocabulary_id)) {
        const index = learnedWordIds.value.indexOf(previousWord.vocabulary_id)
        learnedWordIds.value.splice(index, 1)
        console.log('从已学习列表中移除:', previousWord.word)
      }

      // 从待提交列表中移除该单词的记录
      const pendingIndex = pendingSubmitIds.value.findIndex(
        (item) => item.word.vocabulary_id === previousWord.vocabulary_id,
      )
      if (pendingIndex >= 0) {
        pendingSubmitIds.value.splice(pendingIndex, 1)
        console.log('从待提交列表中移除:', previousWord.word)
      }
    }

    // 回到上一个单词
    currentIndex.value = previousIndex
    currentWord.value = previousWord
    showMeaning.value = false
  }
}

// 提交已学习的单词
const submitLearnedWords = async () => {
  let submitSuccess = false

  // 提交"已掌握"的单词到服务器
  if (learnedWordIds.value.length > 0) {
    try {
      await markWordsAsEasy(bookId, learnedWordIds.value)
      console.log('已提交学习记录:', learnedWordIds.value.length, '个单词')
      submitSuccess = true
    } catch (err) {
      console.error('提交学习记录失败:', err)
      // 提交失败时显示错误信息，但仍然可以继续
      submitSuccess = false
    }
  } else {
    // 如果没有需要提交的"已掌握"单词，也算作成功
    submitSuccess = true
  }

  // 只有在提交成功（或没有需要提交的单词）时，才保存本地记录
  if (submitSuccess || learnedWordIds.value.length === 0) {
    // 保存所有待提交的单词记录到本地
    pendingSubmitIds.value.forEach((item) => {
      saveWordRecord(item.word, item.status)
    })
    console.log('已保存本地记录:', pendingSubmitIds.value.length, '个单词')
  } else {
    console.log('由于提交失败，未保存本地记录，用户下次可以重新学习这些单词')
  }

  // 显示完成状态
  isCompleted.value = true
}

// 加载下一批单词
const loadNextBatch = () => {
  currentPage.value++
  learnedWordIds.value = []
  pendingSubmitIds.value = []
  wordHistory.value = []
  isCompleted.value = false
  loadWords()
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffHours / 24)

  if (diffDays > 0) {
    return `${diffDays}天前`
  } else if (diffHours > 0) {
    return `${diffHours}小时前`
  } else {
    const diffMinutes = Math.floor(diffMs / (1000 * 60))
    return diffMinutes > 0 ? `${diffMinutes}分钟前` : '刚刚'
  }
}

// 返回单词书页面
const goBack = () => {
  router.push('/books')
}
</script>

<style scoped lang="scss">
.study-page {
  min-height: 100vh;
  padding: 20px 0;
  background: var(--background-light);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    flex-wrap: wrap;
    gap: 20px;

    .progress-info {
      display: flex;
      gap: 20px;
      font-size: 14px;
      color: var(--text-secondary);
    }
  }

  .loading {
    text-align: center;
    padding: 60px 20px;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 4px solid var(--border-color);
      border-left: 4px solid var(--primary-color);
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 20px;
    }

    p {
      color: var(--text-secondary);
      font-size: 1.1rem;
    }
  }

  .error-message {
    text-align: center;
    max-width: 500px;
    margin: 60px auto;

    h3 {
      color: #d32f2f;
      margin-bottom: 12px;
    }

    p {
      color: var(--text-secondary);
      line-height: 1.5;
    }
  }

  .completed-state {
    text-align: center;
    max-width: 500px;
    margin: 60px auto;

    .completed-icon {
      font-size: 4rem;
      margin-bottom: 20px;
    }

    h3 {
      color: var(--primary-color);
      margin-bottom: 12px;
    }

    p {
      color: var(--text-secondary);
      margin-bottom: 30px;
    }

    .completed-actions {
      display: flex;
      gap: 16px;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .word-card-container {
    max-width: 800px;
    margin: 0 auto;

    .word-card {
      text-align: center;
      padding: 20px;
      margin-bottom: 20px;

      .word-display {
        margin-bottom: 40px;
        position: relative;

        .btn-undo {
          position: absolute;
          top: 0;
          right: 0;
          width: 36px;
          height: 36px;
          border: 2px solid var(--primary-color);
          background: white;
          color: var(--primary-color);
          border-radius: 50%;
          font-size: 18px;
          font-weight: bold;
          cursor: pointer;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          justify-content: center;

          &:hover {
            background: var(--primary-color);
            color: white;
            transform: scale(1.1);
          }

          &:active {
            transform: scale(0.95);
          }
        }

        .word-text {
          font-size: 3.5rem;
          font-weight: 700;
          color: var(--primary-color);
          margin-bottom: 16px;
          line-height: 1.2;
        }

        .word-accent {
          font-size: 1.5rem;
          color: var(--text-secondary);
          font-family: 'Times New Roman', serif;
        }
      }

      .word-meaning {
        margin-bottom: 40px;
        padding: 30px;
        background: var(--background-light);
        border-radius: 12px;
        border-left: 4px solid var(--primary-color);

        .meaning-content {
          .sense-item {
            margin-bottom: 20px;

            &:last-child {
              margin-bottom: 0;
            }

            .sense-header {
              margin-bottom: 8px;

              .part-of-speech {
                display: inline-block;
                padding: 4px 8px;
                background: var(--primary-color);
                color: white;
                border-radius: 4px;
                font-size: 0.8rem;
                font-weight: 500;
              }
            }

            .definition-cn {
              font-size: 1.2rem;
              line-height: 1.6;
              color: var(--text-primary);
              margin: 8px 0;
              font-weight: 500;
            }

            .definition-en {
              font-size: 1rem;
              line-height: 1.5;
              color: var(--text-secondary);
              margin: 4px 0 0 0;
              font-style: italic;
            }
          }
        }
      }

      .word-controls {
        .reveal-section {
          margin-bottom: 30px;
        }

        .action-section {
          margin-bottom: 30px;

          .action-buttons {
            display: flex;
            gap: 20px;
            justify-content: center;
            flex-wrap: wrap;
          }
        }

        .btn-large {
          padding: 16px 32px;
          font-size: 1.1rem;
          min-width: 160px;
        }
      }
    }

    .shortcuts-hint {
      text-align: center;
      padding: 16px;
      background: rgba(var(--primary-color-rgb), 0.1);
      border-radius: 8px;
      margin-top: 20px;

      p {
        margin: 0;
        font-size: 14px;
        color: var(--text-secondary);
      }
    }
  }

  // 单词记录部分样式
  .word-records-section {
    margin-top: 40px;
    max-width: 1200px;
    margin-left: auto;
    margin-right: auto;

    .records-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      flex-wrap: wrap;
      gap: 16px;

      h3 {
        margin: 0;
        color: var(--primary-color);
        font-size: 1.5rem;
      }

      .records-stats {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;

        .stat-item {
          padding: 4px 8px;
          background: var(--background-light);
          border-radius: 4px;
          font-size: 0.9rem;
          color: var(--text-secondary);

          &.known {
            background: #e8f5e8;
            color: #2e7d32;
          }

          &.unknown {
            background: #ffebee;
            color: #c62828;
          }
        }
      }

      .records-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }
    }

    .records-table-container {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      overflow: hidden;

      .empty-records {
        padding: 60px 20px;
        text-align: center;
        color: var(--text-secondary);
      }

      .records-table-wrapper {
        overflow-x: auto;

        .records-table {
          width: 100%;
          border-collapse: collapse;

          th {
            background: var(--background-light);
            padding: 12px 16px;
            text-align: left;
            font-weight: 600;
            color: var(--text-primary);
            border-bottom: 2px solid var(--border-color);
            white-space: nowrap;
          }

          .record-row {
            border-bottom: 1px solid var(--border-color);
            transition: background-color 0.2s ease;

            &:hover {
              background: rgba(var(--primary-color-rgb), 0.05);
            }

            td {
              padding: 12px 16px;
              vertical-align: top;

              &.word-id {
                font-family: monospace;
                font-size: 0.9rem;
                color: var(--text-secondary);
                max-width: 120px;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              &.word-name {
                font-weight: 600;
                color: var(--primary-color);
                min-width: 100px;
              }

              &.word-translation {
                color: var(--text-primary);
                line-height: 1.4;
                max-width: 200px;
                overflow: hidden;
                text-overflow: ellipsis;
              }

              &.word-status {
                .status-badge {
                  display: inline-block;
                  padding: 4px 8px;
                  border-radius: 12px;
                  font-size: 0.8rem;
                  font-weight: 500;
                  white-space: nowrap;

                  &.known {
                    background: #e8f5e8;
                    color: #2e7d32;
                  }

                  &.unknown {
                    background: #ffebee;
                    color: #c62828;
                  }

                  &.unlearned {
                    background: #f5f5f5;
                    color: #757575;
                  }
                }
              }

              &.learn-time {
                color: var(--text-secondary);
                font-size: 0.9rem;
                white-space: nowrap;
              }

              &.actions {
                width: 60px;
                text-align: center;
              }
            }
          }
        }
      }
    }
  }
}

.btn-small {
  padding: 6px 12px;
  font-size: 0.9rem;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@media (max-width: 768px) {
  .study-page {
    padding: 20px;

    .header {
      flex-direction: column;
      align-items: stretch;
      text-align: center;

      .progress-info {
        justify-content: center;
      }
    }

    .word-card-container {
      .word-card {
        padding: 20px;

        .word-display {
          .btn-undo {
            width: 32px;
            height: 32px;
            font-size: 16px;
          }

          .word-text {
            font-size: 2.5rem;
          }

          .word-accent {
            font-size: 1.2rem;
          }
        }

        .word-meaning {
          padding: 20px;

          .meaning-content {
            .sense-item {
              margin-bottom: 16px;

              .definition-cn {
                font-size: 1rem;
              }

              .definition-en {
                font-size: 0.9rem;
              }
            }
          }
        }

        .word-controls {
          .action-section {
            .action-buttons {
              flex-direction: column;
              align-items: center;
            }
          }

          .btn-large {
            width: 100%;
            max-width: 280px;
          }
        }
      }
    }

    // 移动端记录样式
    .word-records-section {
      .records-header {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;

        h3 {
          text-align: center;
          font-size: 1.3rem;
        }

        .records-stats {
          justify-content: center;
          flex-wrap: wrap;
        }

        .records-actions {
          justify-content: center;
        }
      }

      .records-table-container {
        .records-table-wrapper {
          .records-table {
            font-size: 0.9rem;

            th,
            td {
              padding: 8px 12px;
            }

            .record-row {
              td {
                &.word-id {
                  max-width: 80px;
                  font-size: 0.8rem;
                }

                &.word-name {
                  min-width: 80px;
                }

                &.word-translation {
                  max-width: 150px;
                  font-size: 0.85rem;
                }

                &.word-status {
                  .status-badge {
                    font-size: 0.75rem;
                    padding: 2px 6px;
                  }
                }

                &.learn-time {
                  font-size: 0.8rem;
                }

                &.actions {
                  width: 40px;

                  .btn-delete {
                    width: 20px;
                    height: 20px;
                    font-size: 10px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
